<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理静态页面搭建 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>

      <!-- 放table -->
      <el-table :data="list">
        <el-table-column prop="name" label="角色" align="center">
          <template v-slot="{row}">
            <!-- 根据isEdit 来判断显示不同dom结构 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? "已启用" : "未启用" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放分页器 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          :current-page="pageParams.page"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

    </div>

    <!-- 弹层组件 -->
    <el-dialog width="500px" :visible.sync="showDialog" title="新增角色" @close="btnCancel">
      <!-- 表单 -->
      <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" style="width: 300px" :rows="3" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限弹层组件 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="treeRef"
        check-strictly
        :props="permissionProps"
        :data="permissionData"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="btnPermissionOk">确定</el-button>
          <el-button size="small" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
// 行内编辑功能
// 1. 渲染的数据里得有一个标识 标识编辑模式还是默认模式
// 2. 通过自定义插槽显示编辑状态的表单
// 3. 点击取消需要还原数据 (数据开始的时候准备一个备份)

// 删除
// 1. 点击删除用到 气泡确认框组件
// 2. 点击确认 调用删除接口(封装删除接口)
// 3. 删除的数据是页面最后一个, 需要页码减一  再重新加载 否则 直接重新加载
// 4. 点击取消直接关掉
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0 // 总共多少条
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      permissionProps: {
        label: 'name'
      },
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      // 给每一行加一个编辑标记
      this.list.forEach(item => {
        // item.isEdit=false 错误用法添加的数据没有响应式
        // this.$set(目标对象, 属性名称, 属性值) 这样添加的属性才是有响应式的
        this.$set(item, 'isEdit', false)
        // 备份当前行显示的数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    // 页面变更方法
    changePage(newPage) {
      // 页码参数变更
      this.pageParams.page = newPage
      // 请求新页面数据
      this.getRoleList()
    },
    // 点击确定按钮
    btnOk() {
      // 表单整体验证
      this.$refs.roleForm.validate(async(isOk) => {
        if (isOk) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // 点击取消按钮
    btnCancel() {
      // 重置表单数据
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true // 改变行的状态
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 点击编辑的确定按钮
    async btnEditOk(row) {
      // row.editRow.name && row.editRow.description 必须都有值才能提交
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // row.name = row.editRow.name // 其实没问题,就是Eslint 误判
        // row.state = row.editRow.state
        // row.description = row.editRow.description
        // row.isEdit = false
        // Object.assign(target, source)  合并，后面的对象属性会覆盖前面的对象属性 返回个新对象
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        console.log(row)
      }
    },
    // 点击删除确定
    async confirmDel(id) {
      console.log(id)
      await delRole(id)
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    // 弹出分配权限弹出框
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds

      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    async  btnPermissionOk() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
